package net.chengp.ms.gateway.config;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.util.StandardCharset;

import net.chengp.ms.commons.result.R;
import net.chengp.ms.commons.result.Result;
import reactor.core.publisher.Mono;

/**
 * 鉴权失败
 * 
 * @author chengp
 *
 */
@Component
public class RestfulAccessDeniedHandler implements ServerAccessDeniedHandler {

	@Override
	public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
		ServerHttpResponse response = exchange.getResponse();
		response.setStatusCode(HttpStatus.OK);
		response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
		Result<?> result = R.error(HttpStatus.UNAUTHORIZED.value(), denied.getMessage());
		String body = JSONObject.toJSONString(result);
		DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharset.UTF_8));
		return response.writeWith(Mono.just(buffer));
	}

}
